<?php
declare(strict_types=1);
namespace App\Controller\Api\V1\Cms;

use App\Controller\Api\BaseController;
use App\Model\CmsPost;
use App\Repositories\CmsCategoryRepository;
use App\Repositories\CmsPostRepository;

class ArticleController extends BaseController
{
    public function list(){
        $rows = $this->request->input('rows',10);
        $category_id = (int)$this->request->input('category_id');
        $search=[
            'type'=>['field' => 'type','value' => CmsPost::TYPE_ARTICLE]
        ];
        if($category_id){
            $category = CmsCategoryRepository::getInstance()->getById($category_id);
            if(!$category){
                return $this->response->error(404,'栏目不存在');
            }
            if($category->rgt-$category->lft>1){
                $child_categories = CmsCategoryRepository::getInstance()->getList('*',[[
                    'field' => 'lft',
                    'value' => $category->lft,
                    'method'=>'>='
                ],[
                    'field' => 'rgt',
                    'value' => $category->rgt,
                    'method'=>'<='
                ]],[]);
                $search['category_id']=[
                    'field' => 'category_id',
                    'value' =>$child_categories->pluck('id')->toArray(),
                    'method' => 'in'
                ];
            }else{
                $search['category_id']=[
                    'field' => 'category_id',
                    'value' =>$category->id
                ];
            }
        }
        $orderBy=[[
            'field' => 'id',
            'sort' => 'desc'
        ]];
        $return = CmsPostRepository::getInstance()->getList('*',$search,['limit'=>$rows],$orderBy);
        return $this->response->success($return);
    }

    public function show(){
        $id = (int)$this->request->input('id');
        $article = CmsPostRepository::getInstance()->getById($id);
        return $this->response->success($article);
    }

    public function page(){
        $category_id = (int)$this->request->input('category_id',0);
        if(!$category_id){
            return $this->response->error(1404,'数据不存在');
        }
        $post = CmsPostRepository::getInstance()->one('*',[[
            'field' => 'type',
            'value' => CmsPost::TYPE_PAGE
        ],['field' => 'category_id','value'=>$category_id]]);
        $return = $post?$post:[];
        return $this->response->success($return);
    }
}